{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "078e2471",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-03-18T13:18:37.760538Z",
     "start_time": "2024-03-18T13:18:35.712909Z"
    }
   },
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a81d8a5c",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-03-18T13:25:54.748902Z",
     "start_time": "2024-03-18T13:25:54.742465Z"
    }
   },
   "source": [
    "## no_grad & enable_grad"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61774502",
   "metadata": {},
   "source": [
    "- torch module 前向构建计算图的过程中，不能使用 `torch.enable_grad()`\n",
    "    - 因为外部在推理的时候，大概率还会有 `torch.no_grad` 的 context"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "7cdf2f49",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-03-18T13:18:42.334361Z",
     "start_time": "2024-03-18T13:18:42.326367Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = torch.tensor([1., 2.], requires_grad=True)\n",
    "y = x ** 2\n",
    "y.requires_grad"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2467ef40",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-03-18T13:18:55.687029Z",
     "start_time": "2024-03-18T13:18:55.679115Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "with torch.no_grad():\n",
    "    with torch.enable_grad():\n",
    "        y = x**2\n",
    "y.requires_grad"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
